﻿#region 信息

// Copyright©2014 Rex Rao all rights reserved.
// File name : SoMcCoffee\Sohobloo.SoPermission.Service\GroupService.cs
// Author : Sohobloo
// Create time : 2014/01/26 15:57
// Update time : 2014/02/07 17:46

#endregion

#region 引用

using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using Sohobloo.SoCommon;
using Sohobloo.SoMcCoffee.Service;
using Sohobloo.SoPermission.Data.Repository;
using Sohobloo.SoPermission.Entity;

#endregion

namespace Sohobloo.SoPermission.Service.Impl
{
    [Export(typeof(IGroupService))]
    internal class GroupService : ServiceBase, IGroupService
    {
        #region 属性

        [Import]
        private IGroupRepository GroupRepository { get; set; }

        #endregion 属性

        #region Implementation of IGroupService

        public Group Get(Guid groupId)
        {
            return GroupRepository.GetByKey(groupId);
        }

        public IList<Group> GetList()
        {
            return GroupRepository.Entities.OrderBy(g => g.CreateTime).ToList();
        }

        public OperationResult Add(Group group)
        {
            ArgumentHelper.Instance
                          .CheckNull(group, "group")
                          .CheckEmpty(group.Name, "group.Name");

            var existed = GroupRepository.Entities.Count(g => g.Name == group.Name) > 0;
            if(existed)
            {
                return new OperationResult(OperationResultType.Exist);
            }

            GroupRepository.Insert(group);

            return Commit();
        }

        public OperationResult Update(Group group)
        {
            ArgumentHelper.Instance
                          .CheckNull(group, "group")
                          .CheckEmpty(group.Name, "group.Name");

            var existed = GroupRepository.Entities.Count(g => g.Name == group.Name && g.Id != group.Id) > 0;
            if (existed)
            {
                return new OperationResult(OperationResultType.Exist);
            }

            GroupRepository.Update(group);

            return Commit();
        }

        public OperationResult Delete(Guid groupId)
        {
            GroupRepository.Delete(groupId);

            return Commit();
        }

        #endregion
    }
}